var app = getApp();
var that;

Page({

  data: {
    load: true,
    navBar: [{ label: '已发布', active: true }, { label: '去发布', active: false }],
    array: ['数码配件', '复习资料', '运动乐器', '代步工具', '服装鞋帽', '美妆护肤',],
    goodList: [],
    index: 0,
    xs: '请选择分类',
    lin: 0,
    img_arr: [],
    showimg_arr: '',
    loadText: "下滑试试",
    biaoti: '',
    xiangqing: '',
    jiage: '',
    phone: '',
    dizhi: '',
    weixin: '',
  },

  showLoading() {
    this.setData({
      load: true
    })
  },
  hideLoading() {
    this.setData({
      load: false
    })
  },

  onLoad: function (options) {
    var that = this;
    var query = {
      page: 1,
      size: 7,
      openId: wx.getStorageSync("user").openId,
    }
    that.setData({
      query: query
    })
    that.showLoading()
    that.findOrders(query, false)
  },

  findOrders: function (query, bottom) {
    var that = this;
    app.post('/ops/secondhand/find', query, function (res) {
      if (res.data.code) {
        //成功
        for (var i = 0; i < res.data.params.list.length; i++) {
          res.data.params.list[i].image = res.data.params.list[i].image.split(",");
        }
        if (res.data.params.list.length == 7) {
          that.data.loadText = '下滑试试'
        } else {
          that.data.loadText = '到底了'
        }
        if (bottom == false) {
          that.setData({
            goodList: res.data.params.list,
            loadText: that.data.loadText,
          })
        } else {
          that.setData({
            goodList: that.data.goodList.concat(res.data.params.list),
            loadText: that.data.loadText,
          })
        }
        that.hideLoading()
        wx.hideLoading()
      } else {
        that.hideLoading()
        wx.hideLoading()
      }
    })
  },

  changeStatus: function (e) {
    var that = this;
    if (that.data.goodList[e.currentTarget.dataset.index].isShow == 0) {
      wx.showToast({
        title: '您的二手物品正在审核中，无法进行此操作',
        icon: 'none',
        duration: 2000,
        mask: true,
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '确定已卖出您的二手物品',
        showCancel: true,
        confirmColor: '#3797ee',
        confirmText: '确定',
        success: function (res) {
          if (res.confirm) {
            wx.showLoading({
              title: '加载中',
              mask: true
            })
            app.post('/ops/secondhand/update', {
              id: that.data.goodList[e.currentTarget.dataset.index].id,
              isDelete: 1
            }, function (res) {
              if (res.data.code) {
                var query = that.data.query
                query.page = 1;
                that.findOrders(query, false)
                wx.showToast({
                  title: "恭喜成功卖出",
                  image: '/images/success.png',
                  duration: 2000,
                  mask: true
                })
              } else {
                wx.hideLoading()
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000,
                  mask: true,
                })
              }
            })
          }
        }
      })
    }
  },

  // 表单选择分类
  bindPickerChange: function (e) {
    var address = this.data.array[e.detail.value];
    this.setData({
      xs: address,
      index: e.detail.value
    })
  },
  //标题
  contactbiaoti: function (e) {
    this.data.biaoti = e.detail.value
  },
  //商品详情
  contactxiangqing: function (e) {
    this.data.xiangqing = e.detail.value
  },
  //价格
  contactjiage: function (e) {
    this.data.jiage = e.detail.value
  },
  //联系人电话
  contactphone: function (e) {
    this.data.phone = e.detail.value
  },
  //联系人地址
  contactdizhi: function (e) {
    this.data.dizhi = e.detail.value
  },
  //联系人微信
  contactwx: function (e) {
    this.data.weixin = e.detail.value
  },

  // 顶部切换
  changeBar: function (e) {
    var that = this;
    for (var i = 0; i < that.data.navBar.length; i++) {
      that.data.navBar[i].active = false;
    }
    if (e.currentTarget.dataset.index == 0) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      var query = that.data.query
      query.page = 1;
      that.findOrders(query, false)
    }
    that.data.navBar[e.currentTarget.dataset.index].active = true;
    that.setData({
      navBar: that.data.navBar,
    })
  },

  // 上传图片
  upimg: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success(res) {
        wx.showLoading({
          title: '压缩上传中',
          mask: true
        })
        var uploadImgCount = 0;
        const tempFilePaths = res.tempFilePaths
        wx.getImageInfo({
          src: tempFilePaths[0],
          success: function (res) {
            const ctx = wx.createCanvasContext('attendCanvasId');//创建画布
            var ratio = 2;
            var canvasWidth = res.width
            var canvasHeight = res.height;
            while (canvasWidth > 1050 || canvasHeight > 1750) {
              //比例取整
              canvasWidth = Math.trunc(res.width / ratio)
              canvasHeight = Math.trunc(res.height / ratio)
              ratio++;
            }
            that.setData({
              canvasWidth: canvasWidth,
              canvasHeight: canvasHeight
            })
            ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight);//画布中展示图片大小
            ctx.draw();
            setTimeout(function () {
              wx.canvasToTempFilePath({//把当前画布指定区域的内容导出生成指定大小图片，并返回文件路径
                canvasId: "attendCanvasId",//画布id
                x: 0,
                y: 0,
                width: canvasWidth,
                height: canvasHeight,
                destWidth: canvasWidth / ratio,
                destHeight: canvasHeight / ratio,
                success: function (res) {
                  wx.uploadFile({
                    url: 'https://www.chuyinkeji.cn/ops/filesystem/upfile',
                    filePath: res.tempFilePath,
                    name: 'file',
                    success(res) {
                      if (res.data == "图片不可超过100KB") {
                        wx.showToast({
                          title: '不可超过100KB',
                          image: '/images/tanHao.png',
                          duration: 2000,
                          mask: true
                        })
                      } else {
                        uploadImgCount++;
                        var img_arr = that.data.img_arr;
                        if (img_arr.length >= 9) {
                          wx.showToast({
                            title: '最多支持九张',
                            image: '/images/tanHao.png',
                            duration: 2000,
                            mask: true
                          })
                        } else {
                          img_arr.push(res.data)
                          that.setData({
                            img_arr: img_arr,
                            lin: img_arr.length,
                          });
                          //如果是最后一张,则隐藏等待中  
                          if (uploadImgCount == tempFilePaths.length) {
                            wx.hideLoading();
                          }
                        }
                      }
                    }
                  })
                }
              })
            }, 1000);
          }
        })
      }
    })
  },

  close: function (e) {
    var that = this
    var img_arr = that.data.img_arr
    var lin = that.data.lin
    img_arr.splice(e.currentTarget.dataset.index, 1);
    lin--;
    that.setData({
      img_arr: img_arr,
      lin: lin
    })
  },

  showPic: function (e) {
    var that = this
    var img_arr = that.data.img_arr
    that.setData({
      showimg_arr: img_arr[e.currentTarget.dataset.index]
    })
  },

  close2: function () {
    var that = this
    that.setData({
      showimg_arr: ''
    })
  },
  navToShop: function (e) {
    var that = this
    if (that.data.goodList[e.currentTarget.dataset.index].isShow == 0) {
      wx.showToast({
        title: '您的二手物品正在审核中，无法进行此操作',
        icon: 'none',
        duration: 2000,
        mask: true,
      })
    } else {
      wx.navigateTo({
        url: '/pages/index/mall/details/details?data=' + JSON.stringify(that.data.goodList[e.currentTarget.dataset.index]),
      })
    }
  },

  submit: function () {
    var that = this;
    if (that.data.img_arr.length == 0) {
      wx.showToast({
        title: '至少一张图片',
        image: '/images/tanHao.png',
        duration: 2000,
        mask: true
      })
    } else if (that.data.biaoti == '' || that.data.xiangqing == '' || that.data.jiage == '' || that.data.phone.length != 11 || that.data.dizhi == '' || that.data.weixin == '' || that.data.xs == "请选择分类") {
      wx.showToast({
        title: "未填完整信息",
        image: '/images/tanHao.png',
        duration: 2000,
        mask: true
      })
    } else {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      app.post('/ops/secondhand/add', {
        avatarUrl: wx.getStorageSync("user").avatarUrl,
        category: that.data.xs,
        title: that.data.biaoti,
        text: that.data.dizhi,
        image: that.data.img_arr,
        content: that.data.xiangqing,
        price: that.data.jiage,
        nickName: wx.getStorageSync("user").nickName,
        phone: that.data.phone,
        wxNumber: that.data.weixin,
        openId: wx.getStorageSync("user").openId,
        schoolId: wx.getStorageSync("schoolId"),
        schoolName: wx.getStorageSync("schoolName"),
      }, function (res) {
        if (res.data.code) {
          wx.hideLoading()
          wx.showToast({
            title: "发布成功",
            image: '/images/success.png',
            duration: 2000,
            mask: true
          })
          that.setData({
            biaoti: "",
            xiangqing: "",
            jiage: "",
            name: "",
            phone: "",
            weixin: "",
            dizhi: "",
            img_arr: [],
            lin: 0,
            xs: '请选择分类',
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000,
            mask: true,
          })
        }
      })
    }
  },

  onReachBottom: function () {
    var that = this;
    if (that.data.loadText == "下滑试试" && that.data.navBar[0].active == true) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      var query = that.data.query
      query.page += 1;
      that.findOrders(query, true)
    }
  },

  //转发后显示的内容
  onShareAppMessage: function () {
    return {
      title: '快来和我一起享校园品质生活吧！！',
      path: '/pages/index/index',
    }
  },
})